<template>
  <div class="p-2">
    <transition>
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="模型名称" prop="modelName">
              <el-input v-model="queryParams.modelName" placeholder="请输入模型名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never" class="box-card">
      <template #header>
      <div class="card-header">
          <button-group>
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['system:modelData:add']">新增</el-button>
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['system:modelData:edit']">修改</el-button>
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['system:modelData:remove']">删除</el-button>
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['system:modelData:export']">导出</el-button>
          </button-group>
          <!-- 齿轮图标及下拉复选框 -->
          <el-dropdown trigger="hover">
            <div class="setting-icon-wrapper">
              <el-icon class="setting-icon">
                <Setting />
              </el-icon>
            </div>
            <template #dropdown>
              <div style="padding: 10px; width: 180px;">
                <el-checkbox-group v-model="checkedOptions">
                  <el-checkbox label="边框" />
                  <el-checkbox label="斑马纹" />
                  <el-checkbox label="表头背景" />
                </el-checkbox-group>
              </div>
            </template>
          </el-dropdown>
      </div>
      </template>

      <el-table v-loading="loading"  :data="modelDataList" :border="checkedOptions.includes('边框')"
                :stripe="checkedOptions.includes('斑马纹')"
                :header-cell-style="getHeaderStyle" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="序号" align="center" width="60">
          <template #default="scope">
            <el-tag>{{ scope.$index + 1 }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="模型" align="center" prop="model" />
        <el-table-column label="模型名称" align="center" prop="modelName" />
        <el-table-column label="请求地址" align="center" prop="modelPath" />
        <el-table-column label="应用密钥" align="center" prop="appKey" />
        <el-table-column label="模型参数(JSON格式)" align="center" prop="modelParam" />
        <el-table-column label="支持思考" align="center" prop="thinking">
          <template #default="scope">
            <el-switch v-model="scope.row.thinking" active-value="1" inactive-value="0" />
          </template>
        </el-table-column>
        <el-table-column label="最大上下文长度" align="center" prop="maxContextLength" />
        <el-table-column label="模型介绍" align="center" prop="remark" />
        <el-table-column label="操作" align="center" fixed="right"  class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['system:modelData:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['system:modelData:remove']"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页组件 -->
      <div class="pagination-container">
        <el-pagination
            v-model:current-page="queryParams.pageNum"
            v-model:page-size="queryParams.pageSize"
            :page-sizes="[10, 20, 30, 50]"
            :total="total"
            :background="true"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    <!-- 添加或修改系统模型配置信息对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="60%" append-to-body>
      <el-form ref="modelDataFormRef" :model="form" :rules="rules" label-width="180px">
        <el-form-item label="模型" prop="model">
          <el-input v-model="form.model" placeholder="请输入模型" />
        </el-form-item>
        <el-form-item label="模型名称" prop="modelName">
          <el-input v-model="form.modelName" placeholder="请输入模型名称" />
        </el-form-item>
        <el-form-item label="模型路径" prop="modelPath">
          <el-input v-model="form.modelPath" placeholder="请输入模型路径" />
        </el-form-item>
        <el-form-item label="应用密钥" prop="appKey">
          <el-input v-model="form.appKey" placeholder="请输入应用密钥" />
        </el-form-item>
        <el-form-item label="模型参数(JSON格式)" prop="modelParam">
            <el-input v-model="form.modelParam" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="支持思考" prop="thinking">
          <el-input v-model="form.thinking" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="最大上下文长度" prop="maxContextLength">
          <el-input v-model="form.maxContextLength" placeholder="请输入最大上下文长度" />
        </el-form-item>
        <el-form-item label="模型介绍" prop="remark">
          <el-input type="textarea" v-model="form.remark" placeholder="请输入模型介绍" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="ModelData" lang="ts">
import { listModelData, getModelData, delModelData, addModelData, updateModelData } from '@/api/system/modelData';
import { ModelDataVO, ModelDataQuery, ModelDataForm } from '@/api/system/modelData/types';
import {ComponentInternalInstance} from "@vue/runtime-core";
import ButtonGroup from "@/components/ButtonGroup/index.vue";
import {ref} from "vue";

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const modelDataList = ref<ModelDataVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const modelDataFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: ModelDataForm = {
  id: undefined,
  model: undefined,
  modelName: undefined,
  modelPath: undefined,
  appKey: undefined,
  modelParam: undefined,
  thinking: undefined,
  maxContextLength: undefined
}
const data = reactive<PageData<ModelDataForm, ModelDataQuery>>({
  form: {...initFormData},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    model: undefined,
    modelName: undefined,
    modelPath: undefined,
    appKey: undefined,
    modelParam: undefined,
    thinking: undefined,
    maxContextLength: undefined,
    params: {
    }
  },
  rules: {
    thinking: [
      { required: true, message: "不能为空", trigger: "blur" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

const checkedOptions = ref<string[]>(['边框', '斑马纹', '表头背景'])

// 获取表头样式
const getHeaderStyle = () => {
  if (checkedOptions.value.includes('表头背景')) {
    return { backgroundColor: '#f5f7fa', color: '#333', fontWeight: 'bold' }
  }
  return {}
}
/** 查询系统模型配置信息列表 */
const getList = async () => {
  loading.value = true;
  const res = await listModelData(queryParams.value);
  modelDataList.value = res.rows;
  total.value = res.total;
  loading.value = false;
}

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
}

/** 表单重置 */
const reset = () => {
  form.value = {...initFormData};
  modelDataFormRef.value?.resetFields();
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
}

// 分页大小改变
const handleSizeChange = (val: number) => {
  queryParams.pageSize = val
  getList()
}

// 页码改变
const handleCurrentChange = (val: number) => {
  queryParams.pageNum = val
  getList()
}
/** 多选框选中数据 */
const handleSelectionChange = (selection: ModelDataVO[]) => {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = "添加系统模型配置信息";
}

/** 修改按钮操作 */
const handleUpdate = async (row?: ModelDataVO) => {
  reset();
  const _id = row?.id || ids.value[0]
  const res = await getModelData(_id);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = "修改系统模型配置信息";
}

/** 提交按钮 */
const submitForm = () => {
  modelDataFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id) {
        await updateModelData(form.value).finally(() =>  buttonLoading.value = false);
      } else {
        await addModelData(form.value).finally(() =>  buttonLoading.value = false);
      }
      proxy?.$modal.msgSuccess("操作成功");
      dialog.visible = false;
      await getList();
    }
  });
}

/** 删除按钮操作 */
const handleDelete = async (row?: ModelDataVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除系统模型配置信息编号为"' + _ids + '"的数据项？').finally(() => loading.value = false);
  await delModelData(_ids);
  proxy?.$modal.msgSuccess("删除成功");
  await getList();
}

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download('server/modelData/export', {
    ...queryParams.value
  }, `modelData_${new Date().getTime()}.xlsx`)
}

onMounted(() => {
  getList();
});
</script>
<style scoped>

/* 齿轮图标外层容器 */
.setting-icon-wrapper {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  background-color: #f2f2f2; /* 灰色背景 */
  display: flex;
  justify-content: center;
  align-items: center;
  transition: all 0.2s ease;
  cursor: pointer;
}

/* 悬停效果 */
.setting-icon-wrapper:hover {
  background-color: #e0e0e0; /* 鼠标悬停变深一点 */
}

.setting-icon {
  color: #606266;
  font-size: 18px;
}
</style>
